package com.wy.projectssj.dao.impl;

import com.wy.projectssj.dao.UserDao;
import com.wy.projectssj.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: wy
 * @Date:2019/8/28 21:07
 */
@Repository
public class UserDaoImpl implements UserDao {
      @Autowired
      private JdbcTemplate jdbcTemplate;
    @Override
    public int findAll(){

         String sql="select count(*) from users";
     int count=-1;
        try {
           count = jdbcTemplate.queryForObject(sql,Integer.class);
        } catch (DataAccessException e) {
        }
        return count;
    }
    public List<User> findByCondition(Integer start,Integer rows){
                    String sql="select * from users  limit ?,?";
        List<User>  list=null;
        try {
          list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class), start, rows);
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
            return  list;
    }

    @Override
    public User findById(String id) {
        String sql="select * from users where id=?";
        User user=null;
        try {
             user = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(User.class), id);
        } catch (DataAccessException e) {

        }
        return  user;
    }

    @Override
    public User findOne(User user) {
        String sql="select * from users where username=? and PASSWORD=?";
           User existUser=null;
        try {
            existUser=jdbcTemplate.queryForObject(sql,new BeanPropertyRowMapper<>(User.class),user.getUsername(),
                    user.getPassword());
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        return existUser;
    }

    @Override
    public int save(User user) {
          int result=-1;
            String sql="insert into users values(?,?,?,?,?,?)";
        try {
           result = jdbcTemplate.update(sql, user.getId(), user.getEmail(), user.getUsername(), user.getPassword(), user.getPhoneNum(), user.getStatus());
        } catch (DataAccessException e) {
        }
            return result;
    }

    @Override
    public int delete(String[] ids) {
         int result=-1;
         String s="delete from users where 1=1 and id in (";
        StringBuilder sql=new StringBuilder(s);
        for (int i = 0; i <ids.length ; i++) {
             if(i==ids.length-1){
                 sql.append("?)");
             }else{
                 sql.append("?,");
             }
        }
        try {
            result = jdbcTemplate.update(sql.toString(), ids);
        } catch (DataAccessException e) {

        }
        return result;
    }


}
